<template>
  <el-dialog :visible.sync="dialogVisible" title="新增商品" width="1200px" :close-on-click-modal="false" v-drag2anywhere>
    <div class="title">商品信息</div>
    <el-form :model="formData" label-width="110px" size="mini" :rules="rules" ref="formData">
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="商品编码:" prop="sn">
            <el-input v-model="formData.sn" placeholder="京东SKU,政采编码,自采编码"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="上架渠道:" prop="platform">
            <el-select v-model="formData.platform" @change="handlePlatformChange" style="width: 100%;">
              <el-option v-for="(item,index) in platforms" :label="item.label" :key="item.index" :value="item.label">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合作商名称:" prop="supname">
            <el-select v-model="formData.supname" style="width: 100%;" @change="handleSupChange">
              <el-option v-for="(item,index) in suppliers" :label="item.name" :key="item.index" :value="item.name">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="18">
          <el-form-item label="商品名称:" prop="title">
            <el-input v-model="formData.title" placeholder="商品的标题"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <div style="float: right;">
            <el-form-item label="客户联系人:" prop="client">
              <el-autocomplete v-model="formData.client" placeholder="客户名" :fetch-suggestions="querySearchAsync"
                style="width: 100%;"></el-autocomplete>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-row>
            <el-col :span="12">
              <el-form-item label="品牌:" prop="brand">
                <el-input v-model="formData.brand" placeholder="请输入品牌"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="规格型号:" prop="brand">
                <el-input v-model="formData.model" placeholder="规格型号"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="计量单位:" prop="unit">
                <el-input v-model="formData.unit" placeholder="计量单位"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单价:" prop="price">
                <el-input-number v-model="formData.price" :precision="2" style="width: 100%;">
                </el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="12">
          <el-form-item label="详细参数:">
            <el-input type="textarea" :rows="3" placeholder="商品详细参数" v-model="formData.params" maxlength="500"
              show-word-limit></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col>
        	<el-form-item label="参考链接:">
        		<el-input v-model="formData.cklink" placeholder="其他商城(例如:京东,天猫,淘宝等) 已存在此商品的参考链接">
        		</el-input>
        	</el-form-item>
        </el-col>
        <el-col>
          <el-form-item label="备注信息:">
            <el-input v-model="formData.memo" type="textarea" rows="3" placeholder="备注信息"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <div class="title">产品图片</div>
          <div style="color: rgb(153, 153, 153); font-size: 12px; margin-left: 5px; margin-bottom: 20px;">
            上传图片至少上传三张!</div>
          <div style="margin-bottom: 20px;">
            <el-upload list-type="picture-card" ref="thumbupload" :file-list="thumbuploadConfig.imgList"
              :action="thumbuploadConfig.action" :headers="thumbuploadConfig.headers" :accept="thumbuploadConfig.accept"
              :limit="thumbuploadConfig.limit" :on-change="handleThumbChange" :auto-upload="false"
              :on-remove="handleThumbRemove" :on-exceed="handleThumbLimit" multiple
              :before-remove="handleThumbBeforRemove" :on-preview="handleThumbPreviewPreview">
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog title="图片预览" :visible="previewImg" append-to-body style="text-align: center;"
              @close="previewImg=false">
              <img :src="previewUrl" />
            </el-dialog>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="title">产品资质文件</div>
          <div style="color: rgb(153, 153, 153); font-size: 12px; margin-left: 5px; margin-bottom: 20px;">
            请上传产品线所需资质文件，例如：商标注册证、CCC证书、厂家授权、检测报告等</div>

          <el-upload list-type="picture-card" ref="zzupload" :file-list="zzuploadConfig.imgList"
            :action="zzuploadConfig.action" :headers="zzuploadConfig.headers" :accept="zzuploadConfig.accept"
            :limit="zzuploadConfig.limit" :on-change="handleZZChange" :auto-upload="false" :on-remove="handleZZRemove"
            :on-exceed="handleZZLimit" multiple :before-remove="handleZZBeforRemove"
            :on-preview="handleZZPreviewPreview">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-col>
      </el-row>
      <PDFViewer v-if="pdfVisible" ref="pdfUI"></PDFViewer>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false" size="medium">取 消</el-button>
      <el-button type="primary" size="medium" @click="handleSave">提交申请</el-button>
    </div>
  </el-dialog>
</template>

<script>
  export default {
    data() {
      return {
        formData: {
          sn: '',
          title: '',
          brand: '',
          model: '',
          prams: '',
          supid:-1,
          supname:'',
          platformid: "-1",
          paltform: '',
          unit: '',
          price: 1.00,
          memo: '',
          cklink:''
        },
        suppliers: [],
        platforms: [],
        userinfo: JSON.parse(localStorage.getItem("userinfo")),
        //文件上传相关变量
        thumbuploadConfig: { //产品图片上传
          //文件上传相关参数
          accept: '.jpg,.jpeg,.png',
          limit: 6,
          headers: {
            token: localStorage.getItem('token') != null ? localStorage.getItem('token') : ''
          },
          imgList: [],
          fileList: [],
          removeids: [], //要删除的id
          action: ""
        },
        //文件上传相关变量
        zzuploadConfig: { //产品图片上传
          //文件上传相关参数
          accept: '.pdf,.jpg,.jpeg,.png',
          limit: 10,
          headers: {
            token: localStorage.getItem('token') != null ? localStorage.getItem('token') : ''
          },
          imgList: [],
          fileList: [],
          removeids: [], //要删除的id
          action: ""
        },

        rules: {
          supname: [{
            required: true,
            message: "请选择合作商",
            trigger: "blur"
          }],
          client: [{
            required: true,
            message: "请填写实际联系人",
            trigger: "blur"
          }],
          title: [{
            required: true,
            message: "新增商品名称不能为空",
            trigger: "blur"
          }],
          sn: [{
            required: true,
            message: "京东商品编码不能为空!",
            trigger: "blur"
          }],
          platform: [{
            required: true,
            message: "上架渠道不能空",
            trigger: "blur"
          }],
          price: [{
            required: true,
            message: "商家价格不能为空",
            trigger: "blur"
          }],
          unit: [{
            required: true,
            message: "计量单位不能为空",
            trigger: "blur"
          }],
        },
        types: [{
            label: "京东自营",
          },
          {
            label: "京东慧采",
          },
          {
            label: "政采云",
          }
        ],
        dialogVisible: true,
        pdfVisible: false,
        previewImg: false,
        previewUrl: '',
      }
    },
    mounted() {
      this.loadPlatforms();
      this.loadSuppliers();
    },
    methods: {
      querySearchAsync(str, cb) {
        this.axios.post("api/admin/clientuser/filter", {
          username: str
        }).then(res => {
          if (res.data.code) {
            cb(res.data.data);
          }
        })
      },
      init: function() {
        this.$refs.formData.resetFields(),
          this.formData={
            sn: '',
            title: '',
            brand: '',
            model: '',
            prams: '',
            supid:-1,
            supname:'',
            platformid: "-1",
            paltform: '',
            unit: '',
            price: 1.00,
            memo: '',
            cklink:''
          },
        this.thumbuploadConfig.fileList = [];
        this.$refs.thumbupload.clearFiles();
        this.zzuploadConfig.fileList = [];
        this.$refs.zzupload.clearFiles();
      },
      loadPlatforms: function() {
        this.axios.get("/api/admin/platform/list").then((res) => {
          if (res.status == 200 && res.data.code == 0) {
            this.platforms = res.data.platforms;
          }
        })
      },
      loadSuppliers: function() {
        this.axios.post("api/admin/supplier/list").then((res) => {
          if (res.status == 200 && res.data.code == 0) {
            this.suppliers = res.data.list;
          }
        });
      },
      handlePlatformChange: function(platform) {
        var option = this.platforms.filter(function(cur, index, a) {
          if (cur.label == platform) {
            return cur;
          }
        })[0];
        this.formData.platformid = option.id;
        this.formData.platform = option.label;
      },
      //产品图片上传处理
      handleThumbChange: function(file, list) {
        //判断文件格式和数量
        var ext = file.name.substr(file.name.lastIndexOf('.') + 1).toLowerCase();
        var extarr = ['jpg', 'jpeg', 'png'];
        var sizeok = file.size / 1024 / 1024 < 2;
        if (extarr.lastIndexOf(ext) == -1) {
          this.$message.error("上传文件格式必须为" + extarr.join(","));
          //删除刚上传的文件
          this.thumbuploadConfig.fileList.splice(this.thumbuploadConfig.fileList.length - 1, 1);
          return;
        }
        if (!sizeok) {
          this.$message.error("上传文件大小最大不超过2M");
          this.thumbuploadConfig.fileList.splice(this.thumbuploadConfig.fileList.length - 1, 1);
          return;
        }
        this.thumbuploadConfig.fileList = list;
      },
      handleThumbRemove: function(file) {
        if (file.id) { //如果存储 id即为已经上传好的图片
          console.log('删除了已经上传好的图片');
          this.thumbuploadConfig.rids.push(file.id);
        }
        this.thumbuploadConfig.fileList = fileList;
      },
      handleThumbBeforRemove: function() {
        return this.$confirm("此操作将会删除当前图片，是否继续?", "提示", {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      },
      handleThumbLimit: function() {
        this.$message.warning("最多可上传" + this.thumbuploadConfig.limit + "个文件");

      },
      handleThumbPreviewPreview: function() {
        alert("预览");
      },
      /***资质附件**/
      handleZZChange: function(file, list) {
        //判断文件格式和数量
        var ext = file.name.substr(file.name.lastIndexOf('.') + 1).toLowerCase();
        var extarr = ['jpg', 'jpeg', 'png', "doc", "docx", "xls", "xlsx", "pdf"];
        var sizeok = file.size / 1024 / 1024 < 2;
        if (extarr.lastIndexOf(ext) == -1) {
          this.$message.error("上传文件格式必须为" + extarr.join(","));
          //删除刚上传的文件
          this.zzuploadConfig.fileList.splice(this.zzuploadConfig.fileList.length - 1, 1);
          return;
        }
        if (!sizeok) {
          this.$message.error("上传文件大小最大不超过2M");
          this.zzuploadConfig.fileList.splice(this.zzuploadConfig.fileList.length - 1, 1);
          return;
        }
        this.zzuploadConfig.fileList = list;
      },
      handleZZBeforRemove: function(file, FileList) {
        return this.$confirm("此操作将会删除当前图片，是否继续?", "提示", {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      },
      handleZZRemove: function(file) {
        if (file.id) { //如果存储 id即为已经上传好的图片
          console.log('删除了已经上传好的图片');
          this.zzuploadConfig.removeids.push(file.id);
        }
      },
      handleZZLimit: function() {
        this.$message.warning("最多可上传" + this.zzuploadConfig.limit + "个文件");

      },
      handleZZPreviewPreview: function(file) {
        //预览pdf文件
        console.log(file);
        this.pdfVisible = true;
        this.$nextTick(() => {
          this.$refs.pdfUI.dialogVisible = true;
          this.$refs.pdfUI.initData(file);
        })
      },
      handleSupChange: function(sup) {
        var option = this.suppliers.filter(function(cur, index, a) {
          if (cur.name == sup) {
            return cur;
          }
        })[0];
        this.formData.supid = option.id;
        this.formData.supname = option.name;
      },
      handleSave: function() {
        this.$refs["formData"].validate(ok => {
          if (ok) {
            //检测
            let fd = new FormData();
            fd.append("sn", this.formData.sn);
            fd.append("title", this.formData.title);
            fd.append("platformid", this.formData.platformid);
            fd.append("platform", this.formData.platform);
            fd.append("brand", this.formData.brand);
            fd.append("supid",this.formData.supid);
            fd.append("supname",this.formData.supname);
            fd.append("model", this.formData.model);
            fd.append("client",this.formData.client);
            fd.append("params", this.formData.params);
            fd.append("unit", this.formData.unit);
            fd.append("price", this.formData.price);
            fd.append("memo", this.formData.memo);

            let fid = 0;
            this.thumbuploadConfig.fileList.forEach(file => {
              if (file.raw) {
                fd.append("thumb_" + fid, file.raw);
                fid++;
              }
            });

            fid = 0;
            this.zzuploadConfig.fileList.forEach(file => {
              if (file.raw) {
                fd.append("zizhi_" + fid, file.raw);
                fid++;
              }
            });


            this.$axiosUploader.post("api/admin/good/create", fd).then(res => {
              if (res.status == 200 && res.data.code == 0) {
                this.$emit("closeHandler");
                this.$message({
                  message: "上架申请已提交!",
                  showClose: true,
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.dialogVisible = false;

                  }
                });


                this.thumbuploadConfig.imgList = res.data.thumbs;
                this.zzuploadConfig.imgList = res.data.zizhi;

                this.thumbuploadConfig.fileList = [];
                this.thumbuploadConfig.removeids = [];
                this.zzuploadConfig.fileList = [];
                this.zzuploadConfig.removeids = [];
                this.$refs.thumbupload.clearFiles();
                this.$refs.zzupload.clearFiles();
              } else {
                this.$message.error({
                  message: res.data.msg,
                  duration: 1500,
                  showClose: true
                });
              }
            });

          }
        })
      }
    }
  }
</script>

<style>
  .title {
    position: relative;
    padding-left: 10px;
    margin-bottom: 15px;
    font-size: 14px;
    color: #333;
    font-weight: 700;
  }

  .title:before {
    content: "";
    position: absolute;
    top: 4px;
    left: 0;
    width: 5px;
    height: 65%;
    background-color: #249af3;
  }

  // 上传图片框样式
  .el-upload-list el-upload-list--picture-card {
    height: 96px !important;
    width: 96px !important;
    line-height: 96px !important;
  }

  .el-upload--picture-card {
    height: 96px !important;
    width: 96px !important;
    line-height: 96px !important;
  }

  .el-upload-list__item {
    height: 96px !important;
    width: 96px !important;
    line-height: 96px !important;
  }

  .el-upload-list__item-status-label i {
    position: absolute;
    width: 12x;
    right: 12px;
    top: 0px;
  }

  .el-upload--picture-card {
    height: 96px !important;
    width: 96px !important;
    line-height: 96px !important;
  }

  .el-upload-list__item {
    height: 96px !important;
    width: 96px !important;
    line-height: 96px !important;
    transition: none !important;
  }

  .el-upload-list__item-status-label i {
    position: absolute;
    width: 12x;
    right: 12px;
    top: 0px;
  }
</style>
